package org.chy.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * http://blog.csdn.net/qq_34912469/article/details/75666506
 * 使用jpa定义用户,实现UserDetails接口,用户实体即为SpringSecurity所使用的用户
 * @author chenghy
 * @date 2018年01月07日 12时32分36秒
 * @Description 发上等愿,结中等缘,享下等福;向高处立,就平处坐,从宽处行.
 * @Package org.chy.entity
 */
@Table(name = "sys_user")
@Entity(name = "User")
public class User extends BaseEntity implements UserDetails {

	private static final long serialVersionUID = 3048421986655597567L;

	@Column(name = "username")
	private String username;

	@Column(name = "password")
	private String password;

	/*
	 * FetchType.EAGER:急加载,在加载一个实体的时候,其中定义是急加载的属性(property)和字段(field)会立即从数据库中加载出来;
	 * CascadeType:级联更新.
	 */
	@ManyToMany(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER)
	private List<Role> roles;

	@Override
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		// 将用户角色作为权限
		List<GrantedAuthority> authorities = new ArrayList<>();
		List<Role> roles = this.getRoles();
		for (Role role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getRolename()));
		}
		return authorities;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}
